#!/usr/local/bin/python2.7
# encoding: utf-8
'''
brevityTrainer -- shortdesc

brevityTrainer is a description

It defines classes_and_methods

@author:     user_name

@copyright:  2014 organization_name. All rights reserved.

@license:    license

@contact:    user_email
@deffield    updated: Updated
'''

import sys
import os
import csv_file
import random
from stats import Stats
from questions import Questions

from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
from questions import Questions

__all__ = []
__version__ = 0.1
__date__ = '2014-03-04'
__updated__ = '2014-03-04'
DEBUG = 0
TESTRUN = 0
PROFILE = 0

class CLIError(Exception):
    '''Generic exception to raise and log different fatal errors.'''
    def __init__(self, msg):
        super(CLIError).__init__(type(self))
        self.msg = "E: %s" % msg
    def __str__(self):
        return self.msg
    def __unicode__(self):
        return self.msg

def pick_csv():
    user_input = None
    l = []
    for x in os.listdir('.'):
        if x[-4:] == '.csv':
            l.append(x)
    if len(l) == 0:
        print('ERROR: there is NO brevity csv file in this directory, I need at least one to work with\n\nCurrent directory: {}'.format(os.path.abspath(os.curdir)))
        raw_input()
        sys.exit(4)
    if len(l) == 1:
        return l[0]
    for x in l:
        print('{}: {}'.format(l.index(x)+1, x))
    while not user_input in range(1,len(l)):
        user_input = input('Please select a brevity file to use')
    return l[user_input-1]


def main(argv=None): # IGNORE:C0111
    '''Command line options.'''

    if argv is None:
        argv = sys.argv
    else:
        sys.argv.extend(argv)

    program_name = os.path.basename(sys.argv[0])
    program_version = "v%s" % __version__
    program_build_date = str(__updated__)
    program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date)
    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
    program_license = '''%s

  Created by user_name on %s.
  Copyright 2014 organization_name. All rights reserved.

  Licensed under the Apache License 2.0
  http://www.apache.org/licenses/LICENSE-2.0

  Distributed on an "AS IS" basis without warranties
  or conditions of any kind, either express or implied.

USAGE
''' % (program_shortdesc, str(__date__))

    try:
        # Setup argument parser
        parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter)
        parser.add_argument("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %(default)s]")
#         parser.add_argument("-i", "--in-file", dest="in_file", help="sets file to use as input for brevity definitions", metavar="FILE", default='brevity.csv' )
        parser.add_argument("-q", "--MC-quantity", dest="mc_quantity", help="sets the quantities of options in Multiple Choices", metavar="NUMBER", default=4 )

        # Process arguments
        args = parser.parse_args()

        verbose = args.verbose
#         in_file = args.in_file
        mc_quantity = int(args.mc_quantity)

        if verbose > 0:
            print("Verbose mode on")
        if not isinstance(mc_quantity, int):
            sys.stderr.write("-q must be a number")
            return 3

        in_file = pick_csv()
        stats = Stats(in_file)
        questions = Questions(in_file)
#         print(questions.pick_random())
        print('MENU\n\n1. Regular questions\n2. Harder questions\n3. Ask targeted regular questions based on previous stats (must build some stats first)' \
              '\n4. Ask targeted harder questions based on previous stats (must build some stats first)\n5. Show stats')
        user_input = None
        while not user_input in [1,2,3,4,5]:
            user_input = input('Make your choice: ')
        print('\n\n')
        if user_input == 1:
            while 1:
                questions.ask_regular(4, stats)
        elif user_input == 2:
            while 1:
                questions.ask_the_other_way_around(4, stats)
        elif user_input == 3:
            while 1:
                questions.ask_target(4, stats)
        elif user_input == 4:
            while 1:
                questions.ask_target_the_other_way_around(4, stats)
        elif user_input == 5:
                print(stats)
                raw_input()
    except KeyboardInterrupt:
        ### handle keyboard interrupt ###
        return 0
#     except Exception, e:
#         if DEBUG or TESTRUN:
#             raise(e)
#         indent = len(program_name) * " "
#         sys.stderr.write(program_name + ": " + repr(e) + "\n")
#         sys.stderr.write(indent + "  for help use --help")
#         return 2

if __name__ == "__main__":
    if DEBUG:
        sys.argv.append("-h")
        sys.argv.append("-v")
    if PROFILE:
        import cProfile
        import pstats
        profile_filename = 'brevityTrainer_profile.txt'
        cProfile.run('main()', profile_filename)
        statsfile = open("profile_stats.txt", "wb")
        p = pstats.Stats(profile_filename, stream=statsfile)
        stats = p.strip_dirs().sort_stats('cumulative')
        stats.print_stats()
        statsfile.close()
        sys.exit(0)
    sys.exit(main())